<template>
	<view class="content">

		<view class="input-group">
			<view class="input-row border">
				<text class="title">手机号：</text>
				<m-input class="m-input" type="text" clearable focus v-model="account" placeholder="请输入手机号"></m-input>
			</view>
			<view class="input-row" v-if="loginType=='pwd'">
				<text class="title">密码：</text>
				<m-input type="password" displayable v-model="password" placeholder="请输入密码"></m-input>
			</view>
		</view>

		<view class="btn-row">
			<button type="primary" class="primary" @tap="bindLogin" v-if="loginType=='pwd'">登录</button>
			<button type="primary" class="primary" @tap="openCodeDialog" v-if="loginType=='code'">获取验证码</button>
		</view>

		<view class="uni-flex lyx-flex-justify-content-between">
			<view style="margin-left: 20upx;color: #007AFF;" @tap="changeLogin">{{loginTitle}}</view>
			<view v-if="loginType=='pwd'">
				<text style="margin-right: 4px;">记住密码 | </text>
				<checkbox value="cb" checked="true" @tap="savePwd=!savePwd" /></label>
			</view>
		</view>

		<view class="oauth-row" v-if="hasProvider" v-bind:style="{top: positionTop + 'px'}">
			<view class="oauth-image" v-for="provider in providerList" :key="provider.value">
				<image :src="provider.image" @tap="oauth(provider.value)"></image>
			</view>
		</view>

		<lausirCodeDialog :show="showCodeDialog" :len="6" :autoCountdown="true" :phone="account" v-on:change="change"></lausirCodeDialog>
	</view>
</template>

<script>
	import service from '../../service.js';
	import lausirCodeDialog from '@/components/lausir-codedialog/lausir-codedialog.vue';
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import mInput from '../../components/m-input.vue'

	export default {
		components: {
			mInput,
			lausirCodeDialog
		},
		data() {
			return {
				providerList: [],
				hasProvider: false,
				account: '',
				password: '',
				positionTop: 0,
				showCodeDialog: false,
				code: "1231",
				savePwd: true,
				loginType: 'pwd',
				loginTitle: '验证码登录'
			}
		},
		computed: mapState(['forcedLogin']),
		methods: {
			...mapMutations(['login']),
			initProvider() {
				const filters = ['weixin', 'qq', 'sinaweibo'];
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (res.provider && res.provider.length) {
							for (let i = 0; i < res.provider.length; i++) {
								if (~filters.indexOf(res.provider[i])) {
									this.providerList.push({
										value: res.provider[i],
										image: '../../static/img/' + res.provider[i] + '.png'
									});
								}
							}
							this.hasProvider = true;
						}
					},
					fail: (err) => {
						console.error('获取服务供应商失败：' + JSON.stringify(err));
					}
				});
			},
			initPosition() {
				/**
				 * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
				 * 反向使用 top 进行定位，可以避免此问题。
				 */
				this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
			},
			bindLogin() {
				/**
				 * 客户端对账号信息进行一些必要的校验。
				 * 实际开发中，根据业务需要进行处理，这里仅做示例。
				 */
				if (this.account.length < 2) {
					uni.showToast({
						icon: 'none',
						title: '账号最短为 5 个字符'
					});
					return;
				}
				if (this.password.length < 2) {
					uni.showToast({
						icon: 'none',
						title: '密码最短为 6 个字符'
					});
					return;
				}
				/**
				 * 下面简单模拟下服务端的处理
				 * 检测用户账号密码是否在已注册的用户列表中
				 * 实际开发中，使用 uni.request 将账号信息发送至服务端，客户端在回调函数中获取结果信息。
				 */
				const data = {
					account: this.account,
					password: this.password
				};
				console.log(this.savePwd, '是否保存密码');
				let savePwd = this.savePwd;
				this.$http.login(data).then((res) => {
					if (res.status == 10086) {
						if (savePwd) {
							uni.setStorageSync('user-info', data);
						} else {
							uni.removeStorageSync('user-info');
						}
						this.toMain(this.account)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				})



			},
			oauth(value) {
				uni.login({
					provider: value,
					success: (res) => {
						uni.getUserInfo({
							provider: value,
							success: (infoRes) => {
								/**
								 * 实际开发中，获取用户信息后，需要将信息上报至服务端。
								 * 服务端可以用 userInfo.openId 作为用户的唯一标识新增或绑定用户信息。
								 */
								this.toMain(infoRes.userInfo.nickName);
							}
						});
					},
					fail: (err) => {
						console.error('授权登录失败：' + JSON.stringify(err));
					}
				});
			},
			toMain(userName) {
				this.login(userName);
				/**
				 * 强制登录时使用reLaunch方式跳转过来
				 * 返回首页也使用reLaunch方式
				 */
				uni.reLaunch({
					url: '../main/main',
				});


			},
			change: function(res) {
				var that = this;
				if (res.type == 1) {
					this.code = res.code;
					this.$http.hlCodeLogin(this.account,this.code).then(rest=>{
						if(rest.status == 10086){
							that.toMain(that.account)
						}else{
							uni.showToast({
								title: rest.msg,
								icon: "none"
							});
						}
					})
					that.showCodeDialog = false;
				} else if (res.type == -1) {
					this.code = "请输入验证码";
					this.showCodeDialog = false;
				} else {
					setTimeout(function() {
						res.resendCall()
					}, 3000)
				}


			},
			openCodeDialog: function() {
				var that = this;
				if (this.check_phone(this.account)) {
					this.$http.sendHlMsg(this.account).then(rest => {
						if (rest.status == 1) {
							this.showCodeDialog = true;
						}else{
							uni.showToast({
								title: rest.msg,
								icon: "none"
							});
						}
					})
				}
			},
			changeLogin() {
				if (this.loginType == 'pwd') {
					this.loginType = 'code';
					this.loginTitle = '密码登录';
				} else {
					this.loginType = 'pwd';
					this.loginTitle = '验证码登录';
				}
			},
			check_phone(phone) {
				var reg = /^1[0-9]{10,10}$/;
				if (!reg.test(phone)) {
					uni.showToast({
						title: '填写正确手机号',
						icon: "none"
					});
					return false;
				} else {
					return true;
				}
			}
		},
		onLoad() {
			this.initPosition();
			// this.initProvider();
			let userInfo = uni.getStorageSync('user-info');
			console.log(userInfo)
			if (userInfo.account != false && userInfo.account != undefined && userInfo.account != null) {
				this.account = userInfo.account
				this.password = userInfo.password
			}
		}
	}
</script>

<style>
	.action-row {
		display: flex;
		flex-direction: row;
		justify-content: center;
	}

	.action-row navigator {
		color: #007aff;
		padding: 0 20upx;
	}

	.oauth-row {
		display: flex;
		flex-direction: row;
		justify-content: center;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}

	.oauth-image {
		width: 100upx;
		height: 100upx;
		border: 1upx solid #dddddd;
		border-radius: 100upx;
		margin: 0 40upx;
		background-color: #ffffff;
	}

	.oauth-image image {
		width: 60upx;
		height: 60upx;
		margin: 20upx;
	}

</style>
